﻿var layer_index
var time_index
var host
var port
var key
var time_error_num
var time_success_num
var is_login = false

// 设置登录
function wx_login_request() {
    console.log("调用login开始")
    // 如果当前账号已经登录则不重复登录
    if (!is_login) {
        var index = layer.load(1, {
            shade: [0.1,'#000'] //0.1透明度的白色背景
        });
        console.log("调用login中")
        $.ajax({
            type: "POST",
            url: "index.php?m=cloud&c=wx_login&a=login",
            data: "",
            async: true,
            success: function(result) {
                console.log("调用login结束")
                layer.close(index)
                result = JSON.parse(result)
           
                if(result['state'] == 1) {
                    console.log("操作成功！")
                    host = result['host'];
                    port = result['port'];
                    key  = result['key'];
                    console.log(result);
                    // 显示当前二维码
                    layer_index = layer.open({
                        type: 1,
                        title: '微信登录',
                        maxmin: false,
                        shadeClose: false, // 点击遮罩关闭层
                        skin:'demo-class',
                        area:['350px', '400px'],
                        closeBtn:1,
                        content:'<img style="-webkit-user-select: none; width: 80%; height: 80%; position: absolute; top:50%; left:50%; transform: translate(-50%,-50%);"; src="' + result['QrBase64'] + '">',
                        success: function(layero, index) {},
                        end: function () {},
                        cancel: function () {
                            window.clearInterval(time_index)
                        },
                    });

                    console.log("定时器启动!")
                    time_error_num = 0
                    time_success_num = 0
                    // 定时器不断请求二维码的状态
                    time_index = setInterval(function() {
                        var str = "&host="+host
                            str += "&port="+port
                            str += "&key="+key

                        $.ajax({
                            type: "POST",
                            url: "index.php?m=cloud&c=wx_login&a=get_login_state"+str,
                            data: "",
                            async: true,
                            success: function(result) {
                                time_success_num = time_success_num + 1
                                if (time_success_num > 60) {
                                    eject_title("登录超时!")
                                    window.clearInterval(time_index)
                                    layer.close(layer_index)
                                } else {
                                    console.log('成功!')
                                    result = JSON.parse(result)
                                    if (result['state'] > 0) {
                                        console.log("定时器关闭!")
                                        window.clearInterval(time_index)
                                        layer.close(layer_index)
                                        eject_title("微信登录成功!")
                                        get_wx_data()
                                    } else if (result['state'] == -1) {
                                        location.href = "index.php?m=cloud&c=cloud_login&a=login_main"
                                        eject_title("登录超时!") 
                                    } else if (result['state'] < 0) {
                                        console.log("定时器关闭!")
                                        console.log(result)
                                        window.clearInterval(time_index)
                                        layer.close(layer_index)
                                        eject_title("二维码操作超时!")
                                    }
                                }
                            },

                            error: function (result) {
                                console.log('失败!', time_error_num)
                                result = JSON.parse(result)
                                console.log(result)
                                if (time_error_num > 3) {
                                    console.log("定时器关闭!")
                                    window.clearInterval(time_index)
                                    layer.close(layer_index)
                                    eject_title("数据错误, 请重新请求!")
                                }
                            }
                        })
                    }, 2000);
                } else if (result['state'] == -1) {
                    location.href = "index.php?m=cloud&c=cloud_login&a=login_main"
                    eject_title("登录超时!") 
                }
            },
            error: function() {
                layer.close(index)
                eject_title("获取二维码失败, 请重新获取!")
            }
        }).responseText;
    } else {
        eject_title("账号已存在,请勿重复登录")
    }
}

// 设置退出
function wx_exit_request() {
    if (is_login) {
        var index = layer.load(1, {
            shade: [0.1, '#000'] //0.1透明度的白色背景
        });

        $.ajax({
            type: "POST",
            url: "index.php?m=cloud&c=wx_login&a=exit",
            data: "",
            async: true,
            success: function(result) {
                result = JSON.parse(result)
                if (result['state'] > 0) {
                    console.log(result);
                    is_login = false
                    // 设置头像
                    $(".div2-left").html("<img class= 'img' src = 'public/cloud/statics/img/icon.jpg' alt='' >")
                    // 设置名字
                    $(".div2-r1").html("")
                    // 设置推送状态
                    $(".div2-r2").html("暂未登陆")
                    if (result['state'] == 1) {
                        eject_title("退出成功!")
                    } else {
                        eject_title(result['msg'])
                    }
                } else if (result['state'] == -1) {
                    location.href = "index.php?m=cloud&c=cloud_login&a=login_main";
                } else {
                    eject_title(result['msg'])
                }
                layer.close(index)
            },
            error: function() {
                layer.close(index)
                eject_title("退出失败!")
            }
        })
    } else {
        eject_title("当前没有登录账号!")
    }
}

// 获取当前机器人微信信息
function get_wx_data() {
    $.ajax({
        type: "POST",
        url: "index.php?m=cloud&c=wx_login&a=get_wx_data",
        data: "",
        async: false,
        success: function(result) {
            result = JSON.parse(result)
            if (result['state'] == 1) {
                is_login = true

                // 设置头像
                if (result['head_url']) {
                    $(".div2-left").html("<img class = 'img' src = '"+result['head_url']+"' alt = '' >")
                }

                // 设置名字
                if (result['nick_name']) {
                    $(".div2-r1").html(result['nick_name'])
                    $(".div2-r2").html("已经登陆")
                }
                
            } else if (result['state'] == -1) {
                location.href = "index.php?m=cloud&c=cloud_login&a=login_main";
            } else if (result['state'] < 0) {
                eject_title(result['msg'])
            }
        },
    })
}

// 判断是否新群需要创建
function create_new_group() {
    if (!is_login) {
        eject_title('请先登录微信!')
        return
    }

    // Ajax调用处理
    $.ajax({
        type: "POST",
        url: "index.php?m=cloud&c=cloud_my&a=create_new_group",
        data: "",
        async: true,
        success: function(result) {
            result = JSON.parse(result)
            if (result['state'] == 1) {
                location.href = "index.php?m=cloud&c=cloud_my&a=my_main";       
            } else if (result['state'] == 0) {
                eject_title(result['msg'])
            } else if (result['state'] == -1) {
                location.href = "index.php?m=cloud&c=cloud_login&a=login_main";
            } else {
                eject_title(result['msg'])
            }
        },
    }).responseText;
}

// 弹出提示框
function eject_title(str, fun) {
    if (fun) {
        layer.msg(str, function(){fun()})
    } else {
        layer.msg(str)
    }
}

// 更新心跳
function update_heart_beat(frist) {
    if (is_login || frist) {
        $.ajax({
            type: "POST",
            url: "index.php?m=cloud&c=wx_login&a=get_heart_beat",
            data: "",
            async: true,
            success: function(result) {
                console.log(result)
                result = JSON.parse(result)
                if (result['state'] == 0) {
                    location.href = "index.php?m=cloud&c=cloud_my&a=my_main";
                } else if (result['state'] == -1) {
                    location.href = "index.php?m=cloud&c=cloud_login&a=login_main";
                } else if (result['state'] == -2) {
                    is_login = false
                }
            },
        })
    }
}

// 页面在加载之前会先调用该函数
$().ready(function() {
    // update_heart_beat(true)
    get_wx_data()
    // setInterval(update_heart_beat, 30*1000);
});